<?php 
namespace Home\Model;
use Think\Model;

class UsersModel extends Model{
	
	protected $trunTableName;
	protected $userDate;
	
	function __construct(){	
		parent::__construct();
		
	}
	
	/*用户注册*/
	function toSignUp($data, $type = null){
		
		if($data == null) return "注册信息传入错误!请重试!";
		
		$userid = $this->where("username = '$data[username]'")->getField("userid");
		if($userid != null) return "该用户名已被注册!请重试!";
		
		$status = $this->data($data)->filter('strip_tags')->add($data);
		
		if(!$status) return "注册信息写入错误!请重试!";
		
		if($type == null)
			return $this->toLogin($data);
		else 
			return 10;
		
	}
	
	/*用户登录*/
	function toLogin($data,$remeberMe){
		
		$userData = $this->where("username = '$data[username]' and password = '$data[password]'")->find();
		
		if($userData == null) return "用户名或密码错误!请重试!";
		if($userData['valid'] != 1) return "该用户已被禁用，请与管理员联系!";
		
		$user['lastip']	= get_client_ip();
		$user['lastdate']	= strtotime(date("Y-m-d H:i:s"));
		$user['logincount']	= $userData['logincount']+1;
		
		$this->where("userid = ".$userData['userid'])->data($user)->save($user);
		
		session(C('WEB_PRE').'user',$userData);
		
		if($remeberMe == 1){
			cookie(C('WEB_PRE').'username',$data['username'],C('COOKIE_TIME'));
			cookie(C('WEB_PRE').'password',$data['password'],C('COOKIE_TIME'));
		}
		
		return 10;
	}
	
	/*更改密码*/
	function changePwd($data){
		
		$userData = session(C('WEB_PRE').'user');
		
		if($userData['password'] != md5($data['old_pwd'])) return "原密码错误!";
		
		$newData['password'] = md5($data['new_pwd']);
		
		$status = $this->data($newData)->where("userid = ".(int)$userData['userid'])->save();
		
		if(!$status) return "用户信息写入错误!";
		
		$userData = $this->where("userid = ".(int)$userData['userid'])->find();
		
		session(C('WEB_PRE')."user",$userData);
		
		return 10;
	}
	
	/*更改信息*/
	function reInfo($data){
		
		$userData = session(C('WEB_PRE').'user');
		
		$status = $this->data($data)->filter("strip_tags")->where("userid = ".(int)$userData[userid])->save();
		
		if(!$status) return "用户信息写入错误!";
		
		$userData = $this->where("userid = ".(int)$userData['userid'])->find();
		
		session(C('WEB_PRE')."user",$userData);
		
		return 10;
		
	}
	
}
